<template>
  <div class="page-container">
    <a-card :bodyStyle="{ padding: '0' }" :bordered="false">
      <div class="mb-5 table-summary-box">
        <a-alert class="items-start">
          <template #icon>
            <icon-exclamation-circle />
          </template>
          <div> 1.同步订单：根据您配置的渠道及账号密码，定时自动同步各平台订单，包含订单信息、承租人信息、车辆信息、费用信息等。 </div>
          <div>
            2.同步库存：当车辆存在排车、改排、续租、换车、提前还车、取消订单等操作时，系统将自动去各个平台反占库存，防止车辆超售/超卖，造成到店无车情况发生。
          </div>
          <div class="flex">
            <div> 3.门店/车型/车辆/员工匹配：</div>
            <div>
              <div>如OTA平台侧配置的门店/车型/车辆/员工名称同商户在启程系统侧创建的门店/车型/车辆/员工名称一致时，系统会自动建立关联；</div>
              <div>如OTA平台侧与启程系统门店/车型/车辆/员工名称对应关系为N对1时，可以手动操作关联。</div>
              <div>此功能会支持到平台订单同步及库存同步的及时准确性。</div>
            </div>
          </div>
          <div>4.如您选择的维护方式为：自动维护，新创建账号后已完成的历史订单不会自动抓取，请手动操作【同步订单】。</div>
        </a-alert>
      </div>
    </a-card>

    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />

    <table-index :table="table" @loadData="loadData">
      <!-- 失败原因 -->
      <template #errorMsgList="{ record }">
        <div v-for="errorMsg in record.errorMsgList" :key="errorMsg" class="errMsg">
          <span class="mr-1.5">
            {{ errorMsg.msg }}
          </span>
          <a
            v-if="errorMsgPermission(record, errorMsg.type)"
            class="error-btn"
            type="text"
            size="small"
            @click="() => onClickError(record, errorMsg.type)"
          >
            {{ getErrorMsgBtn(errorMsg.type) }}
            <icon-right />
          </a>
        </div>
      </template>
      <!-- 账号状态 -->
      <template #status="{ record }">
        <status-tag :value="record.status" :label="record.statusName" />
        <!-- <div class="flex items-center status-wrapper">
          <span class="status-icon" :class="statusClassName(record.status)"></span>
          <span>{{ record.statusName }}</span>
        </div> -->
      </template>
      <!-- 同步库存 -->
      <template #syncStore="{ record }">
        <a-switch
          :disabled="
            userStore.syncInventory.channelStoreSync === 0 || ((record.sourceId == 7 || record.sourceId == 8) && record.status == 3)
          "
          v-model="record.syncStore"
          :checked-value="1"
          :unchecked-value="0"
          @change="(evt: any) => onSyncSotreChange(evt, record)"
        />
        <div class="syncStore-box" v-if="record.syncStore === 1">
          <a-space size="large">
            <a-checkbox-group
              :disabled="(record.sourceId == 7 || record.sourceId == 8) && record.status == 3"
              @change="onSyncSotreChange(record.syncStore, record)"
              v-model="record.syncStoreBizList"
              :options="options"
            />
          </a-space>
        </div>
      </template>
    </table-index>
  </div>

  <a-modal width="45vw" title="账号校验" v-model:visible="smsVisiable" :mask-closable="false" @close="handleSmsCancel">
    <page-form ref="smsFormRef" :model="smsForm" layout="vertical">
      <page-form-row :gutter="24">
        <page-form-item size="1/2">
          已发送至手机号：
          <template v-if="itemOption?.sourceId === 5">
            {{ feizhuPhone }}
          </template>
          <template v-else>
            {{ itemOption?.username }}
          </template>
        </page-form-item>
      </page-form-row>
      <page-form-row :gutter="24">
        <page-form-item field="smsCode" :rules="{ required: true, message: '请输入' }" size="1/2" label="验证码" required>
          <i-input v-model="smsForm.smsCode" placeholder="请输入" :max-length="20" />
          <a-button v-if="itemOption?.sourceId !== 5" type="primary" :disabled="disabled" @click="onGetVerifySmsCode">
            {{ btnText }}
          </a-button>
        </page-form-item>
      </page-form-row>
    </page-form>
    <template #footer>
      <a-space>
        <a-button @click="handleSmsCancel">关闭</a-button>
        <a-button type="primary" :loading="smsButtonLoading" @click="handleSmsOk">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <!-- 订单同步等待弹窗 -->
  <a-modal width="45vw" title="提示" title-align="start" :closable="false" :mask-closable="false" v-model:visible="waitVisiable">
    <div>订单正在同步中，订单同步完成后，会发送推送通知OTA渠道订单负责人</div>
    <template #footer>
      <a-space>
        <a-button @click="waitVisiable = false">关闭</a-button>
      </a-space>
    </template>
  </a-modal>

  <!-- 队列弹窗 -->
  <TaskModal v-model="taskVisiable" @cancel="handelTaskConfig" />

  <a-modal width="45vw" title="修改密码" :mask-closable="false" v-model:visible="changePwdVisiable" @close="onPwdModalClose">
    <div class="modal-body">
      <a-alert style="margin-bottom: 20px">
        <template #icon>
          <icon-exclamation-circle />
        </template>
        同步OTA渠道数据需要一定时间，如账号密码错误，会在列表内提示
      </a-alert>
      <page-form layout="vertical" ref="changePwdFormRef" :model="form" :rules="rules" autocomplete="new-password">
        <page-form-row :gutter="24">
          <page-form-item field="username" size="1/2" label="渠道账号" required>
            <i-input v-model="form.username" placeholder="请输入" :max-length="30" autocomplete="new-password" />
          </page-form-item>
          <page-form-item field="password" size="1/2" label="渠道密码" required>
            <a-input-password
              v-model:visibility="visibility"
              v-model="form.password"
              placeholder="请输入"
              :max-length="20"
              allow-clear
              autocomplete="new-password"
            />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click=";(changePwdVisiable = false), changePwdFormRef.resetFields()">关闭</a-button>
        <a-button type="primary" :loading="changePwdButtonLoading" @click="handelChangePwdOk">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <!-- 同步选择时间弹窗 -->
  <SyncOrderModal v-model="syncOrderVisible" :channel-id="syncOrderId" v-model:loading="syncOrderLoading" @confirm="onSyncOrderConfirm" />
</template>
<script setup lang="ts" name="OtaChannelList">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import {
    getOtaList,
    changeStatus,
    syncOrder,
    updatePassword,
    verifyLogin,
    getOtaDetail,
    verifySmsCode,
    updateSyncStatus,
    stopVerify,
  } from '@/api/business/ota'
  import { Modal, Message } from '@arco-design/web-vue'
  import useNavigate from '@/hooks/useNavigate'
  import { onUnmounted } from 'vue'
  import useUserStore from '@/store/modules/user'
  import TaskModal from './form/modal-box/task-modal.vue'
  import SyncOrderModal from './components/syncOrderModal.vue'
  import useCountLoop from './hooks/useCountLoop'
  import { loop, clear } from './utils'
  import { usePermission } from '@/hooks/usePermission'
  import { usePageDict } from '@/hooks/useDict'
  const dict = usePageDict('otaChannelDict')

  const { navigateTo } = useNavigate()

  const { doLoop, clearLoop, btnText, disabled } = useCountLoop()

  const userStore = useUserStore() as any
  userStore.setEpDetail()

  const visibility = ref(true)
  const changePwdFormRef = ref()
  const smsFormRef = ref()

  const form = ref({
    username: '',
    password: '',
  })
  const smsForm = ref({
    smsCode: '',
  })
  const rules = ref({
    username: [{ required: true, message: '请输入', trigger: 'blur' }],
    password: [{ required: true, message: '请输入', trigger: 'blur' }],
  })

  const syncOrderLoading = ref(false)
  const syncOrderVisible = ref(false)
  const taskVisiable = ref(false)
  const smsVisiable = ref(false)
  const changePwdButtonLoading = ref(false)
  const changePwdVisiable = ref(false)
  const waitVisiable = ref(false)

  const itemOption = ref()

  const errorMsgPermission = (record: any, value: number) => {
    switch (value) {
      case 1:
      case 2:
      case 3:
      case 6:
      case 7:
        if (record.status == 1 || record.status == 0) {
          return usePermission('svms:business:channel:ota.edit')
        } else {
          return false
        }
      case 4:
        if (record.status == 1 || record.status == 0) {
          return usePermission('svms:business:channel:ota.change-password')
        } else {
          return false
        }
      case 5:
        if ((record.status == 1 || record.status == 0) && (record.sourceId === 2 || record.sourceId === 5) && record.verifyFlag === 0) {
          return usePermission('svms:business:channel:ota.smscode')
        } else {
          return false
        }
      default:
        return false
    }
  }

  const getErrorMsgBtn = (value: number) => {
    switch (value) {
      case 1:
      case 2:
      case 3:
      case 6:
      case 7:
        return '去匹配'
      case 4:
        return '去修改密码'
      case 5:
        return '去验证'
    }
  }

  const statusClassName = (status: number) => {
    switch (status) {
      case 1:
        return 'open'
      case 2:
      case 3:
        return 'pending'
      case 0:
        return 'close'
    }
  }

  const options = [
    {
      label: '短租',
      value: 1,
    },
    {
      label: '长租',
      value: 2,
    },
  ]

  const feizhuPhone = ref('')
  // 详情接口函数
  const getDetailFn = async () => {
    const { result } = await getOtaDetail({ id: itemOption.value.id })
    const { extraDataJson } = result
    const { verifyPhone } = extraDataJson
    feizhuPhone.value = verifyPhone
    return result
  }

  /** 输入验证码 */
  const enterCode = (record: any) => {
    itemOption.value = record

    if (record.sourceId === 2) {
      smsVisiable.value = true
    }
    if (record.sourceId === 5) {
      Message.info('正在验证中...')

      taskVisiable.value = true // 打开队列弹窗

      getVerifyCode()
        .then(() => {
          loop(
            (response: any) => {
              if (response.verifyFlag === 1) {
                taskVisiable.value = false
                Message.info('该渠道账号无需进行验证，即将刷新...')
                setTimeout(() => {
                  loadData()
                }, 500)
              } else if (response.extraDataJson?.errMsg) {
                taskVisiable.value = false
                Message.error(response.extraDataJson?.errMsg)

                /** 新增飞猪渠道需要根据verifyType判断是否短信弹窗 */
              } else if (response.extraDataJson?.verifyType >= 1) {
                taskVisiable.value = false
                smsVisiable.value = true
              }
            },
            (error: any) => {
              taskVisiable.value = false
              Message.error(error.message)
            },
            getDetailFn,
            true
          )
        })
        .catch((error: any) => {
          console.log(error, 'error')
          taskVisiable.value = false
          Message.error(error.message)
        })
    }
  }

  const syncOrderId = ref()
  const table = useTable({
    columns: [
      { title: '渠道名称', dataIndex: 'sourceName', fixed: 'left', width: 90 },
      { title: '渠道信息匹配情况', dataIndex: 'errorMsgList', slotName: 'errorMsgList', width: 280 },
      { title: '运营主体', dataIndex: 'subject', width: 120 },
      { title: '渠道账号', dataIndex: 'username', width: 120 },
      { title: '账号状态', dataIndex: 'status', slotName: 'status', width: 120 },
      { title: '最后同步时间', dataIndex: 'lastFinishTime', width: 170 },
      {
        title: '同步库存',
        dataIndex: 'syncStore',
        slotName: 'syncStore',
        titleTooltipContent: '当车辆被其他平台订单占用时，开启同步库存，系统将自动占用库存，防止车辆超售/超卖，造成到店无车情况发生',
        width: 110,
      },
    ],
    tableLoading: false,
    operates: [
      {
        label: '同步订单',
        permission: 'svms:business:channel:ota.sync-order',
        show: (record: any) => record.status == 1 && record.sourceId != 7 && record.sourceId != 8,
        method: (record: any) => {
          syncOrderVisible.value = true
          syncOrderId.value = record
        },
      },
      {
        label: '查看/编辑',
        permission: 'svms:business:channel:ota.edit',
        // 账号状态为同步中时，需支持操作：查看/编辑、修改密码
        show: (record: any) => record.status == 1 || record.status == 0 || record.status == 3 || record.status == 2,
        method: (record: any) => {
          navigateTo(
            `/channel-setting/edit/${record.id}?sourceId=${record.sourceId}&sourceStatus=${record.status}`,
            `${record.subject}-编辑渠道`
          )
        },
      },
      {
        label: '输入验证码',
        permission: 'svms:business:channel:ota.smscode',
        show: (record: any) =>
          (record.status == 1 || record.status == 0) && (record.sourceId === 2 || record.sourceId === 5) && record.verifyFlag === 0,
        method: (record: any) => {
          console.log(record)
          enterCode(record)
        },
      },
      {
        label: '修改密码',
        permission: 'svms:business:channel:ota.change-password',
        show: (record: any) => (record.status == 1 || record.status == 0 || record.status == 2) && record.sourceId != 7 && record.sourceId != 8,
        method: (record: any) => {
          console.log(record)
          itemOption.value = record
          form.value.username = record.username
          form.value.password = record.password
          changePwdVisiable.value = true
        },
      },
      {
        label: '开启',
        permission: 'svms:business:channel:ota.open',
        show: (record: any) => record.status == 0,
        method: (record: any) => {
          toggleStatusFn(record, '启用')
        },
      },
      {
        label: '关闭',
        permission: 'svms:business:channel:ota.close',
        show: (record: any) => record.status == 1,
        method: (record: any) => {
          toggleStatusFn(record, '关闭')
        },
      },
    ],
    buttons: [
      {
        type: 'primary',
        icon: 'plus',
        label: '新增渠道',
        permission: 'svms:business:channel:ota.add',
        method: () => {
          navigateTo('/channel-setting/create', '新增渠道')
        },
      },
    ],
  })
  const queryParam = reactive({})
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '渠道名称', prop: 'sourceIdList', type: 'a-select', multiple: true, options: dict.thirdpartySourceEnum },
      { label: '运营主体', prop: 'subjectLike', type: 'a-input' },
      { label: '渠道账号', prop: 'usernameLike', type: 'a-input' },
      { label: '账号状态', prop: 'status', placeholder: '请选择', type: 'a-select', options: dict.accountStatusEnum },
    ]
  })
  const loadData = useFetchTableDataApi(table, queryParam, getOtaList)

  const onClickError = (record: any, type: number) => {
    console.log('record', record, type)

    switch (type) {
      case 1:
      case 2:
      case 3:
        navigateTo(`/channel-setting/edit/${record.id}?tabKey=${type + 1}`, `${record.subject}-编辑渠道`)
        return
      case 4:
        itemOption.value = record
        form.value.username = record.username
        form.value.password = record.password
        changePwdVisiable.value = true
        return
      case 5:
        enterCode(record)
        return
      case 6:
        navigateTo(`/channel-setting/edit/${record.id}?tabKey=${type - 1}`, `${record.subject}-编辑渠道`)
        return
    }
  }

  const onSyncSotreChange = (checked: any, record: any) => {
    record.syncStore = checked
    updateSyncStatus({ id: record.id, syncStore: record.syncStore, syncStoreBizList: record.syncStoreBizList })
      .then(() => {
        Message.success('修改成功')
      })
      .catch((error: any) => {
        record.syncStore = 0
        console.log(error, 'error')
      })
  }

  const onPwdModalClose = () => {
    visibility.value = true
    changePwdFormRef.value.resetFields()
  }
  // syncOrder({ id: syncOrderId.value.id, ...value })

  const onSyncOrderConfirm = (value: any) => {
    syncOrder(value)
      .then(() => {
        Message.success('开始同步，请稍后查看')
        syncOrderLoading.value = false
        syncOrderVisible.value = false
        loadData()
      })
      .catch(() => {
        syncOrderLoading.value = false
      })
  }

  // 终止获取短信验证流程
  const stopVerifyId = ref()
  // 验证校验码
  const onGetVerifySmsCode = () => {
    const isLoop = doLoop()
    if (isLoop) {
      return
    }

    getVerifyCode()
      .then()
      .catch((error: any) => {
        console.log(error, 'error')
        Message.error(error.message)
      })
  }

  const getVerifyCode = () => {
    return new Promise((resolve, reject) => {
      verifyLogin({ id: itemOption.value.id })
        .then((res: any) => {
          console.log(res, 'verifyLogin')
          stopVerifyId.value = res.result // 飞猪队列有返回id
          resolve(res)
        })
        .catch((err: any) => {
          // Message.error(err.message)
          console.log(err, 'err')
          reject(err)
        })
    })
  }

  const handleSmsCancel = () => {
    smsVisiable.value = false
    smsFormRef.value.resetFields()
    btnText.value = '获取验证码'
    disabled.value = false
    clearLoop()

    if (stopVerifyId.value) {
      stopVerify({ id: itemOption.value.id, msgId: stopVerifyId.value }).then((res: any) => {
        console.log(res, 'stopVerify')
      })
    }
  }

  const smsButtonLoading = ref(false)
  const handleSmsOk = () => {
    smsFormRef.value.validate(async (valid: any) => {
      smsButtonLoading.value = true
      if (!valid) {
        try {
          const result = await verifySmsCode({ id: itemOption.value.id, smsCode: smsForm.value.smsCode })
          console.log(result, 'handleSmsOk')

          if (itemOption.value.sourceId === 2 || itemOption.value.sourceId === 5) {
            loop(
              (response: any) => {
                if (response.closeMsg) {
                  smsButtonLoading.value = false
                  Message.error(response.closeMsg)
                } else if (response.verifyFlag === 1) {
                  smsVisiable.value = false
                  smsButtonLoading.value = false
                  smsFormRef.value.resetFields()
                  loadData()
                } else if (response.extraDataJson?.errMsg) {
                  smsButtonLoading.value = false
                  Message.error(response.extraDataJson?.errMsg)

                  /** 飞猪平台已经弹出短信弹窗则不需要再判断verifyType */
                } else if (response?.loop) {
                  response.loop()
                }
              },
              (error: any) => {
                smsButtonLoading.value = false
                Message.error(error.message)
              },
              getDetailFn
            )
          } else {
            smsVisiable.value = false
            smsButtonLoading.value = false
            smsFormRef.value.resetFields()
            loadData()
          }
        } catch (err: any) {
          Message.error(err.message)
          smsButtonLoading.value = false
        }
      } else {
        smsButtonLoading.value = false
      }
    })
  }

  // 关闭，请稍后尝试
  const handelTaskConfig = () => {
    stopVerify({ msgId: stopVerifyId.value, id: itemOption.value.id }).then((res: any) => {
      console.log(res, 'handelTaskConfig')
      taskVisiable.value = false
      clear()
    })
  }

  const handelChangePwdOk = () => {
    changePwdFormRef.value.validate((valid: any) => {
      if (!valid) {
        changePwdButtonLoading.value = true
        updatePassword({ id: itemOption.value.id, ...form.value })
          .then((res: any) => {
            console.log(res, itemOption, 'handelChangePwdOk')
            Message.success('修改成功')
            changePwdVisiable.value = false
            changePwdFormRef.value.resetFields()
            loadData()
          })
          .catch((error: any) => {
            console.log(error, 'error')
          })
          .finally(() => {
            changePwdButtonLoading.value = false
          })
      }
    })
  }

  const toggleStatusFn = (record: any, operateName: string) => {
    new Promise<void>((resolve) => {
      if (operateName == '启用') {
        if (record.sourceId == 7 || record.sourceId == 8) {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `请确认是否开启${record.sourceName}OTA渠道，开启后，订单和库存将自动同步`,
            onOk: () => {
              resolve()
            },
          })
        } else {
          // 停用需要加二次确认
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `请确认是否开启当前OTA渠道，开启后，订单会自动同步且需要一定时间，如同步失败，会在列表内提示。`,
            onOk: () => {
              resolve()
            },
          })
        }
      } else {
        if (record.sourceId == 7 || record.sourceId == 8) {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `请确认是否关闭当前OTA渠道，停用后${record.sourceName}渠道订单和库存将不会再同步？`,
            onOk: () => {
              resolve()
            },
          })
        } else {
          // 停用需要加二次确认
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `请确认是否关闭当前OTA渠道，停用后此OTA渠道订单和车辆信息将不会再同步？`,
            onOk: () => {
              resolve()
            },
          })
        }
      }
    }).then(() => {
      const param = {
        id: record.id,
        status: operateName == '启用' ? 1 : 0,
      }
      changeStatus(param).then(() => {
        Message.success(`${operateName}成功`)
        // 手动更改状态
        loadData()
      })
    })
  }

  onMounted(() => {
    loadData()
  })

  onUnmounted(() => {
    btnText.value = '获取验证码'
    disabled.value = false
    clearLoop()
    clear()
  })
</script>
<style scoped lang="less">
  .errMsg {
    color: rgba(245, 63, 63, 1);
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }
  }
  .error-btn {
    min-width: 55px;
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    transition: all 0.1s cubic-bezier(0, 0, 1, 1);
    user-select: none;
    font-size: 14px;
    border-radius: var(--border-radius-small);
    color: rgb(var(--primary-6));
  }
  .syncStore-box {
    display: flex;
    align-items: center;
    margin-top: 15px;
    :deep(.arco-checkbox-group .arco-checkbox) {
      &:last-child {
        margin-right: 0;
      }
    }
  }
  .status-wrapper {
    height: 28px;
    .status-icon {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
      &.open {
        background: #00b42a;
      }
      &.close {
        background: #ea0000;
      }
      &.pending {
        background: rgba(22, 93, 255, 1);
      }
    }
  }
  .modal-body {
    overflow: hidden;
  }
</style>
